package com.rom.cpptest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }
    class cinc
    {
        int add (int a ,int b)
        {
            Log.d("cinc.add" , String.valueOf(a+b));
            return  a+b;
        }
        void cinc()
        {
            int a=0;
            a=a+1243;
        }
    }
    public cinc c=new cinc();
    public  String  add_non_static_log(String log)
    {
        System.out.println(log);
        Log.d("MyReceiver add_non_static_log" , log);
        return log;
    }
    public static String  add_log(String log)
    {
        System.out.println(log);
        Log.d("MyReceiver" , log);
        return log;
    }
    /**
     * 获取用户权限
     */
    private void permissionRequest() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.INTERNET
            };

            List<String> mPermissionList = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);
                }
            }

            if (mPermissionList.isEmpty()) {// 全部允许
                // toMain(); //执行下一步操作
            } else {//存在未允许的权限
                String[] mPermissions = mPermissionList.toArray(new String[mPermissionList.size()]);
                ActivityCompat.requestPermissions(MainActivity.this, mPermissions, 1001);
            }
        }
    }
    TextView result_text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        permissionRequest();
        //setContentView(R.layout.activity_main);

        LinearLayout layout = new LinearLayout(this);
        setContentView(layout);
        layout.setOrientation(LinearLayout.VERTICAL);
        //result_text = (TextView)findViewById(R.id.sample_text);
        result_text = new TextView(this);
        result_text.setMaxHeight(2400);
        result_text.setMovementMethod(ScrollingMovementMethod.getInstance());


        Button bn_java_root_detect=new Button(this);
        bn_java_root_detect.setText("java root检测");
        bn_java_root_detect.setLayoutParams(new ViewGroup.LayoutParams(
                600,
                ViewGroup.LayoutParams.WRAP_CONTENT));

        Button bn_libc_root_detecct=new Button(this);
        bn_libc_root_detecct.setText("libc root检测");
        bn_libc_root_detecct.setLayoutParams(new ViewGroup.LayoutParams(
                600,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Button bn_svc_root_detect=new Button(this);
        bn_svc_root_detect.setText("svc root检测");
        bn_svc_root_detect.setLayoutParams(new ViewGroup.LayoutParams(
                600,
                ViewGroup.LayoutParams.WRAP_CONTENT));

        Button bn_svc_cpu_detect=new Button(this);
        bn_svc_cpu_detect.setText("svc方法获取cpu信息");
        bn_svc_cpu_detect.setLayoutParams(new ViewGroup.LayoutParams(
                600,
                ViewGroup.LayoutParams.WRAP_CONTENT));

        Button bn_libc_cpu_detect=new Button(this);
        bn_libc_cpu_detect.setText("libc方法获取cpu信息");
        bn_libc_cpu_detect.setLayoutParams(new ViewGroup.LayoutParams(
                600,
                ViewGroup.LayoutParams.WRAP_CONTENT));

        Button bn_java_cpu_detect=new Button(this);
        bn_java_cpu_detect.setText("java方法获取cpu信息");
        bn_java_cpu_detect.setLayoutParams(new ViewGroup.LayoutParams(
                600,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Button httpurlconnectiondemo=new Button(this);
        httpurlconnectiondemo.setText("java httpUrlConnection");
        httpurlconnectiondemo.setLayoutParams(new ViewGroup.LayoutParams(
                600,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        layout.addView(bn_java_cpu_detect);
        layout.addView(bn_libc_cpu_detect);
        layout.addView(bn_svc_cpu_detect);
        layout.addView(bn_java_root_detect);
        layout.addView(bn_libc_root_detecct);
        layout.addView(bn_svc_root_detect);
        layout.addView(httpurlconnectiondemo);

        layout.addView(result_text);
        //setContentView(R.layout.activity_main);
        bn_java_root_detect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result_text.scrollTo(0,0);
                boolean broot=detectRoot_inJava();
                if(broot) {
                    result_text.setText(" java 方法有 root 不执行add 函数");

                }
                else {

                    result_text.setText(" libC open方法 没有 root 执行 \n" );
                }
            }
        });
        bn_libc_root_detecct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result_text.scrollTo(0,0);
                result_text.setText(stringFromJNI());
                boolean broot=detectRoot_libC();
                if(broot) {

                    result_text.setText(" libC open方法 有 root 不执行add 函数");
                    //int x=add(4,5);
                }
                else {

                    result_text.setText(" libC open方法 没有 root 执行 \n" );
                }
            }
        });
        bn_svc_root_detect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result_text.scrollTo(0,0);
                //boolean broot= CheckSysUtils.isRoot();
                boolean broot= detectRoot_svc();
                if(broot) {
                    result_text.setText(" svc方法有 root 不执行add 函数");

                    //int x=add(4,5);
                }
                else {

                    result_text.setText(" svc 没有 root 执行 可更新运行 \n" );
                }

            }
        });

        bn_svc_cpu_detect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result_text.scrollTo(0,0);
                    result_text.setText(get_cpuinfo_svc());

            }
        });

        bn_libc_cpu_detect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result_text.scrollTo(0,0);
                result_text.setText(get_cpuinfo_libc());

            }
        });

        bn_java_cpu_detect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                result_text.scrollTo(0,0);
                result_text.setText(getCpuInfo_java());

            }
        });

        httpurlconnectiondemo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                            try {
                                URL url = new URL("https://www.baidu.com");
                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                                connection.setRequestMethod("GET");
                                connection.setRequestProperty("token","firefox");
                                connection.setConnectTimeout(8000);
                                connection.setReadTimeout(8000);
                                connection.connect(); // 开始连接
                                InputStream in = connection.getInputStream();
                                //if(in.available() > 0){

                                // 每次写入1024字节
                                int bufferSize = 1024;
                                byte[] buffer = new byte[bufferSize];
                                StringBuffer sb = new StringBuffer();
                                while ((in.read(buffer)) != -1) {
                                    sb.append(new String(buffer));
                                }
                                Log.d("MyReceiver ", sb.length()+ "\r\n"+sb.toString());
                                connection.disconnect();

                                result_text.scrollTo(0,0);
                                String result=new String(sb).substring(0,64);
                                result=result.replace('\n',' ');
                                result=result.replace('\r',' ');
                                result_text.setText(String.valueOf(result));

                                // }

                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                    }
                }).start();

            }
        });
    }


    public static String getCpuInfo_java() {
        String cpuinfo="";
        try{
            String cmd = "/proc/cpuinfo";
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(cmd)), 1000);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null){
                sb.append(line).append("\n");
            }
            cpuinfo=sb.toString();
            reader.close();
        }catch (Exception ex){
            ex.printStackTrace();

        }
      return  cpuinfo;

        //下面代码在有的机器上不好用
        //ShellAdbUtils.CommandResult commandResult = ShellAdbUtils.execCommand("cat /proc/cpuinfo", false);
       // return commandResult == null ? "" : commandResult.successMsg;
    }
public boolean detectRoot_inJava()
{
    boolean bExists = false;
    try {
        File f = new File("/system/bin/su");
        bExists = f.exists();
        if(bExists)
            add_log("File exists: " + bExists);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return bExists;
}
    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();

    public native int add(int a, int b);

    public native boolean detectRoot_svc();
    public native boolean detectRoot_libC();
    public native String get_cpuinfo_svc();
    public native String get_cpuinfo_libc();
}